package domain;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.json.JsonValue.ValueType;

/**
 * Send a request to JCDecaux
 * 
 * @author Smouha
 * 
 */
public class JCDecauxQuery {

	public Map<Integer, JCDecauxObject> sendRequest() throws IOException {
		String sURL = "https://api.jcdecaux.com/vls/v1/stations?contract=paris&apiKey=07c7589f7f1255ffddbc55ec716d368ef5774a84";
		URL url = new URL(sURL);

		InputStream is = url.openStream();

		JsonReader rdr = Json.createReader(is);
		JsonArray array = rdr.readArray();

		is.close();

		Map<Integer, JCDecauxObject> mapRes = new HashMap<Integer, JCDecauxObject>();

		for (JsonValue value : array) {
			ValueType vt = value.getValueType();
			if (vt == ValueType.OBJECT) {
				JsonObject jsonObj = (JsonObject) value;
				int number = jsonObj.getInt("number");
				String sStatus = jsonObj.getString("status");
				EStatus status = EStatus.strToValue(sStatus);
				int bikeStands = jsonObj.getInt("bike_stands");
				int avalbBikeStands = jsonObj.getInt("available_bike_stands");
				int avalbBikes = jsonObj.getInt("available_bikes");

				JCDecauxObject jcDecauxObj = new JCDecauxObject(number, status,
						bikeStands, avalbBikes, avalbBikeStands);

				mapRes.put(number, jcDecauxObj);

			}
		}

		return mapRes;
	}
}
